package com.sparrow.socket.http.manager;

import com.sparrow.socket.http.anno.HttpPacketClass;
import com.sparrow.socket.http.anno.HttpMethod;
import com.sparrow.socket.http.bean.HttpMethodWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class HttpPacketManager implements BeanPostProcessor {

    private Map<Integer, HttpMethodWrapper> wrapperMap = new HashMap<>();

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        if (clazz.isAnnotationPresent(HttpPacketClass.class)) {
            for (Method method : clazz.getDeclaredMethods()) {
                if (!method.isAnnotationPresent(HttpMethod.class)) {
                    continue;
                }
                HttpMethod httpMethodAnno = method.getAnnotation(HttpMethod.class);
                if (httpMethodAnno == null) {
                    continue;
                }
                HttpMethodWrapper wrapper = new HttpMethodWrapper(bean, method);
                int packetId = httpMethodAnno.packetId();
                HttpMethodWrapper pre = wrapperMap.put(packetId, wrapper);
                if (pre != null) {
                    throw new RuntimeException(String.format("http方法id=%d 重复注册", packetId));
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    public HttpMethodWrapper getHttpMethodWrapper(int packetId) {
        return wrapperMap.get(packetId);
    }
}
